<script lang="ts" setup>
import type { ProcessModel } from '#/api/workflow';

import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Form,
  FormItem,
  Input,
  Modal,
  Select,
  SelectOption,
  Space,
  Upload,
  message,
} from 'ant-design-vue';

const { TextArea } = Input;

import {
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons-vue';

import {
  createProcessModelApi,
  deleteProcessModelApi,
  deployProcessModelApi,
  exportProcessModelApi,
  getProcessModelListApi,
  importProcessModelApi,
  updateProcessModelApi,
} from '#/api/workflow';

const router = useRouter();

// 查询参数
const queryParams = reactive({
  name: undefined,
  key: undefined,
  category: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid<ProcessModel>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'name',
        title: '模型名称',
        minWidth: 200,
      },
      {
        field: 'key',
        title: '模型Key',
        minWidth: 150,
      },
      {
        field: 'category',
        title: '分类',
        width: 120,
      },
      {
        field: 'version',
        title: '版本',
        width: 80,
      },
      {
        field: 'createTime',
        title: '创建时间',
        minWidth: 180,
      },
      {
        field: 'action',
        title: '操作',
        width: 320,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 表单相关
const modalVisible = ref(false);
const currentModel = ref<ProcessModel | undefined>();
const formRef = ref();
const formData = reactive<ProcessModel>({
  name: '',
  key: '',
  category: '',
  description: '',
});

const formRules = {
  name: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  key: [{ required: true, message: '请输入模型Key', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
};

// 查询模型列表
async function fetchModelList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getProcessModelListApi(queryParams);
    gridApi.setState({
      gridOptions: {
        data: data.list,
        loading: false,
        pagerConfig: {
          currentPage: data.pageNum,
          pageSize: data.pageSize,
          total: data.total,
        },
      },
    });
  } catch (error: any) {
    message.error(error?.msg || '查询失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  fetchModelList();
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchModelList();
}

// 重置
function handleReset() {
  queryParams.name = undefined;
  queryParams.key = undefined;
  queryParams.category = undefined;
  queryParams.pageNum = 1;
  fetchModelList();
}

// 新增
function handleAdd() {
  currentModel.value = undefined;
  Object.assign(formData, {
    name: '',
    key: '',
    category: '',
    description: '',
  });
  modalVisible.value = true;
}

// 编辑
function handleEdit(record: ProcessModel) {
  currentModel.value = { ...record };
  Object.assign(formData, record);
  modalVisible.value = true;
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate();
    if (currentModel.value?.id) {
      await updateProcessModelApi({ ...formData, id: currentModel.value.id });
      message.success('更新成功');
    } else {
      await createProcessModelApi(formData);
      message.success('创建成功');
    }
    modalVisible.value = false;
    await fetchModelList();
  } catch (error: any) {
    if (error?.msg) {
      message.error(error.msg);
    }
  }
}

// 删除
function handleDelete(record: ProcessModel) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除模型"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deleteProcessModelApi(record.id!);
        message.success('删除成功');
        await fetchModelList();
      } catch (error: any) {
        message.error(error?.msg || '删除失败');
      }
    },
  });
}

// 设计
function handleDesign(record: ProcessModel) {
  // 跳转到设计器页面
  router.push(`/workflow/model/designer/${record.id}`);
}

// 部署
function handleDeploy(record: ProcessModel) {
  Modal.confirm({
    title: '确认部署',
    content: `确定要部署模型"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deployProcessModelApi(record.id!);
        message.success('部署成功');
      } catch (error: any) {
        message.error(error?.msg || '部署失败');
      }
    },
  });
}

// 导出
async function handleExport(record: ProcessModel) {
  try {
    const blob = await exportProcessModelApi(record.id!);
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${record.key}.bpmn`;
    link.click();
    URL.revokeObjectURL(url);
    message.success('导出成功');
  } catch (error: any) {
    message.error(error?.msg || '导出失败');
  }
}

// 导入
async function handleImport(file: File) {
  try {
    await importProcessModelApi(file);
    message.success('导入成功');
    await fetchModelList();
  } catch (error: any) {
    message.error(error?.msg || '导入失败');
  }
  return false; // 阻止默认上传行为
}

// 页面加载时自动获取列表数据
onMounted(() => {
  fetchModelList();
});
</script>

<template>
  <Page
    title="流程模型管理"
    description="管理流程模型，支持创建、编辑、部署流程"
  >
    <div class="flex h-full flex-col">
      <!-- 查询表单 -->
      <div class="mb-4 rounded-lg bg-white p-4">
        <Form layout="inline" :model="queryParams">
          <FormItem label="模型名称">
            <Input
              v-model:value="queryParams.name"
              placeholder="请输入模型名称"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="模型Key">
            <Input
              v-model:value="queryParams.key"
              placeholder="请输入模型Key"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="分类">
            <Select
              v-model:value="queryParams.category"
              placeholder="请选择分类"
              allow-clear
              style="width: 150px"
            >
              <SelectOption value="OA">OA办公</SelectOption>
              <SelectOption value="HR">人事管理</SelectOption>
              <SelectOption value="FINANCE">财务管理</SelectOption>
              <SelectOption value="OTHER">其他</SelectOption>
            </Select>
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleQuery">
                <template #icon><SearchOutlined /></template>
                查询
              </Button>
              <Button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>

      <!-- 操作按钮 -->
      <div class="mb-4">
        <Space>
          <Button v-permission="'workflow:model:add'" type="primary" @click="handleAdd">
            <template #icon><PlusOutlined /></template>
            新建模型
          </Button>
          <Upload
            :show-upload-list="false"
            :before-upload="handleImport"
            accept=".bpmn,.xml"
          >
            <Button v-permission="'workflow:model:import'">
              <template #icon><UploadOutlined /></template>
              导入模型
            </Button>
          </Upload>
        </Space>
      </div>

      <!-- 数据表格 -->
      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'workflow:model:design'"
                type="link"
                size="small"
                @click="handleDesign(row)"
              >
                设计
              </Button>
              <Button
                v-permission="'workflow:model:deploy'"
                type="link"
                size="small"
                @click="handleDeploy(row)"
              >
                部署
              </Button>
              <Button
                v-permission="'workflow:model:export'"
                type="link"
                size="small"
                @click="handleExport(row)"
              >
                导出
              </Button>
              <Button
                v-permission="'workflow:model:edit'"
                type="link"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </Button>
              <Button
                v-permission="'workflow:model:delete'"
                type="link"
                size="small"
                danger
                @click="handleDelete(row)"
              >
                删除
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </div>

    <!-- 模型表单弹窗 -->
    <Modal
      v-model:open="modalVisible"
      :title="currentModel?.id ? '编辑模型' : '新建模型'"
      width="600px"
      @ok="handleSubmit"
    >
      <Form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <FormItem label="模型名称" name="name">
          <Input v-model:value="formData.name" placeholder="请输入模型名称" />
        </FormItem>
        <FormItem label="模型Key" name="key">
          <Input
            v-model:value="formData.key"
            placeholder="请输入模型Key（唯一标识）"
            :disabled="!!currentModel?.id"
          />
        </FormItem>
        <FormItem label="分类" name="category">
          <Select v-model:value="formData.category" placeholder="请选择分类">
            <SelectOption value="OA">OA办公</SelectOption>
            <SelectOption value="HR">人事管理</SelectOption>
            <SelectOption value="FINANCE">财务管理</SelectOption>
            <SelectOption value="OTHER">其他</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="描述" name="description">
          <TextArea
            v-model:value="formData.description"
            :rows="4"
            placeholder="请输入模型描述"
          />
        </FormItem>
      </Form>
    </Modal>
  </Page>
</template>

